from contextlib import contextmanager

@contextmanager
def open_file(file_path, mode):
    print(f"Opening file '{file_path}'")
    file = open(file_path, mode)
    try:
        yield file  # 返回文件对象
    finally:
        print(f"Closing file '{file_path}'")
        file.close()  # 确保文件关闭

# 使用上下文管理器
with open_file('example.txt', 'w') as f:
    f.write('Hello, World!')
    print("File written successfully")

# 文件已自动关闭


# 运行下面代码后，操作系统可能会因为文件句柄耗尽而抛出错误：OSError: [Errno 24] Too many open files
# # 不关闭文件的代码
# for i in range(10000):
#     f = open(f'file_{i}.txt', 'w')
#     f.write('Hello, World!')
#     # 没有调用 f.close()